<template>
  <div>
    <EvDrawer
      :drawer="drawer"
      :title="drawerTitle"
      size="45%"
      @handleClose="handleClose"
      @handleCancel="handleCancel"
      @handleConfirm="handleConfirm"
      :showConfirm="!disabled"
    >
      <el-form ref="form" :model="form" :rules="rules" :disabled="disabled" label-width="auto" size="medium">
        <div class="partTitle">任务信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务编号" prop="code">
              <el-input v-model="form.code" disabled placeholder="请输入任务编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入任务名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="level">
              <el-select style="display: block" v-model="form.level" placeholder="请选择优先级" clearable>
                <el-option v-for="item in levelList" :key="item.k" :label="item.v" :value="item.k"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="planBegin">
              <el-date-picker
                style="width: 100%"
                v-model="form.planBegin"
                @change="(value) => computeWorkTime('begin', value)"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                :picker-options="pickerOptionsStart"
                placeholder="选择计划开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="responsibleId">
              <el-select
                style="display: block"
                v-model="form.responsibleId"
                filterable
                clearable
                placeholder="请选择负责人"
                @clear="handlePersonClear"
                @change="handlePersonChange"
              >
                <el-option v-for="item in personList" :key="item.value" :label="item.name" :value="item.value">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.department }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束时间" prop="planEnd">
              <el-date-picker
                style="width: 100%"
                v-model="form.planEnd"
                @change="(value) => computeWorkTime('end', value)"
                type="datetime"
                :picker-options="pickerOptionsEnd"
                format="yyyy-MM-dd HH:mm"
                placeholder="请选择计划结束时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划工期" prop="workTime">
              <el-input v-model="form.workTime" placeholder="请选择计划工期" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产进度" prop="point">
              <el-input v-model="form.point" placeholder="请输入生产进度" disabled>
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="beginTime">
              <el-date-picker
                style="width: 100%"
                v-model="form.beginTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                :picker-options="pickerOptionsActBegin"
                placeholder="请选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                style="width: 100%"
                v-model="form.endTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                :picker-options="pickerOptionsActEnd"
                placeholder="请选择结束时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="partTitle">业务信息</div>
        <el-row :gutter="20">
          <div></div>
        </el-row>
      </el-form>
    </EvDrawer>
  </div>
</template>
<script>
import util, { autoCode } from "@/utils/util";
export default {
  data() {
    return {
      drawer: false,
      drawerTitle: "",
      disabled: false,
      // 表单数据
      form: {
        code: "",
        title: "",
        busSource: "plan",
      },
      microservices: "function-manufacture-data",
      resource: "TaskManage",
      rules: {
        code: [
          {
            required: true,
            message: "工单任务编号不能为空",
            trigger: "change",
          },
        ],
        title: [
          {
            required: true,
            message: "工单任务名称不能为空",
            trigger: "change",
          },
        ],
        materialName: [{ required: true, message: "生产产品不能为空", trigger: "change" }],
        planQuantity: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("计划数量不能为空"));
              }
              if (value <= 0 || value >>> 0 !== parseFloat(value)) {
                callback(new Error("计划生产数量只能为正整数"));
              } else if (value > 100000) {
                callback(new Error("计划生产数量超出正常范围"));
              }
              {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
      // 开始结束日期限制
      pickerOptionsStart: {
        disabledDate: (time) => {
          if (this.form.planEnd) {
            return time.getTime() >= new Date(this.form.planEnd).getTime();
          }
        },
      },
      // 结束日期限制
      pickerOptionsEnd: {
        disabledDate: (time) => {
          if (this.form.planBegin) {
            return time.getTime() <= new Date(this.form.planBegin).getTime();
          }
        },
      },
      // 开始日期限制
      pickerOptionsActBegin: {
        disabledDate: (time) => {
          if (this.form.EndTime) {
            return time.getTime() <= new Date(this.form.EndTime).getTime();
          }
        },
      },
      // 结束日期限制
      pickerOptionsActEnd: {
        disabledDate: (time) => {
          if (this.form.beginTime) {
            return time.getTime() <= new Date(this.form.beginTime).getTime();
          }
        },
      },
      levelList: [],
      personList: [],
    };
  },
  methods: {
    async open(params, id) {
      const { drawerTitle, disabled } = params;
      this.drawerTitle = drawerTitle;
      this.disabled = disabled;
      await this.getObjectById(id);
      this.getDictionarys();
      this.getPersonList();
      this.drawer = true;
    },
    async getObjectById(id) {
      if (!id) {
        this.form = {
          title: "",
          code: "",
          busSource: "plan",
        };
        this.getSerialNumber();
        return;
      }
      await this.$server()
        .getObjectById(this.microservices, this.resource, id)
        .then((result) => {
          this.form = result;
        })
        .catch(function (response) {
          this.$message.error(response.data.message);
        });
    },
    // 获取自动编号
    getSerialNumber() {
      autoCode
        .getSerialNumber("TASK", 1)
        .then((err) => {
          this.serialNumbers = err;
          this.$set(this.form, "code", this.serialNumbers[0].serialNumber);
          this.confirmSerialNumber();
        })
        .catch((err) => {
          this.$message.error(err.data.message);
        });
    },
    confirmSerialNumber() {
      autoCode.confirmCode(this.serialNumbers);
    },
    // 人员
    getPersonList() {
      this.$server()
        .query("function-user", "DepartmentUser", {}, null, null, false)
        .then((res) => {
          this.personList = res.list.map((item) => {
            const obj = {};
            obj.name = item.data.name;
            obj.value = item.data.id.toString();
            obj.department = item.department.title;
            return obj;
          });
          this.personList = this.personList.filter((item) => item.name !== null);
        })
        .catch((err) => {
          this.$message.error(err.data.message);
        });
    },
    // 选择人员
    handlePersonChange(e) {
      let item = this.personList.find((item) => item.value == e);
      let obj = {
        type: "user",
        responsible: 1,
        sourseId: item.value,
        sourseName: item.name,
      };
      this.form.responsibleUser = obj;
      this.form.taskSourseDTOList = [];
      if (this.form.taskSourseDTOList && this.form.taskSourseDTOList.length > 0) {
        this.form.taskSourseDTOList = this.form.taskSourseDTOList.filter((item) => item.type !== "用户");
      }
      this.form.taskSourseDTOList.push(obj);
    },
    // 清除人员选择
    handlePersonClear() {
      this.form.responsibleUser = {};
    },

    computeWorkTime(name, value) {
      if (value == null) {
        this.form.workTime = null;
      }
      if (name == "end") {
        this.form.planEnd = value;
      }
      if (name == "begin") {
        this.form.planBegin = value;
      }
      if (this.form.planBegin && this.form.planEnd) {
        const workTime = util.timeDiff(this.form.planBegin, this.form.planEnd);
        this.$set(this.form, "workTime", workTime);
      }
    },
    getDictionarys() {
      let titles = "任务优先级,工单来源";
      this.$server()
        .batchQueryDictionary(titles)
        .then((response) => {
          this.workOrderSourseList = response.filter((f) => f.title === "工单来源")[0].details;
          this.levelList = response.filter((f) => f.title === "任务优先级")[0].details;
        })
        .catch((response) => {
          this.$message.error(response.data.message);
        });
    },
    handleCancel() {
      this.drawer = false;
    },
    handleClose() {
      this.drawer = false;
    },
    handleConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let obj = JSON.parse(JSON.stringify(this.form));
          const isUpdate = obj.id ? true : false;
          this.$server()
            .addOrUpdate(this.microservices, this.resource, obj, isUpdate, 1)
            .then(() => {
              this.$message.success(isUpdate ? "编辑成功" : "新增成功");
              this.drawer = false;
              this.$emit("handleConfirm");
            })
            .catch((err) => {
              this.$message.error(err.data.message);
            });
        } else {
          return false;
        }
      });
      //   具体类型任务需要走addTask 和 updateTask 接口
      //   if (isUpdate) {
      //     self
      //       .$server()
      //       .erdfRequest(`/server/${self.microservices}/base/${self.resource}/updateTask`, [obj], "POST")
      //       .then((res) => {
      //         self.$notify("保存成功", "success");
      //         self.cancel();
      //       })
      //       .catch((err) => {
      //         console.log(err);
      //         self.$notify(err.data.message, "error");
      //       });
      //   } else {
      //     self
      //       .$server()
      //       .erdfRequest(`/server/${self.microservices}/base/${self.resource}/addTask`, [obj], "POST")
      //       .then((res) => {
      //         this.$server().erdfRequest(
      //           "/server/business-manufacture/base/RuleNumberSerial/confirm",
      //           [this.serialNumberObj],
      //           "post"
      //         );
      //         self.$notify("保存成功", "success");
      //         self.cancel();
      //       })
      //       .catch((err) => {
      //         console.log(err);
      //         self.$notify(err.data.message, "error");
      //       });
      //   }
    },
  },
};
</script>
  <style lang="scss" scoped>
.partTitle {
  font-size: 16px;
  font-weight: 700;
  color: #333;
  margin: 12px 0;
}
</style>